import 'dart:io';

import 'package:dio/dio.dart';
import 'package:dio/io.dart';

import '../DioExtens.dart';
import '../common/test_page.dart';

class TimeoutTestPage extends TestPage {
  TimeoutTestPage(super.title){
    test('连接超时时捕获DioException', () {
      Dio dio = getDio();
      dio.options.baseUrl = 'https://httpbun.com/';
      dio.options.connectTimeout = Duration(milliseconds: 3);

      expect(
        dio.get('/drip-lines?delay=2'),
        '',
      );
    });

    test('接收超时时捕获DioException', () {
      Dio dio = getDio();
      dio.options.baseUrl = 'https://httpbun.com/';
      dio.options.receiveTimeout = Duration(milliseconds: 10);

      expect(
        dio.get(
          '/bytes/${1024 * 1024 * 20}',
          options: Options(responseType: ResponseType.stream),
        ),
        '',
      );
    });

    test('接收超时>请求持续时间时无DioException', () async {
      Dio dio = getDio();
      dio.options.baseUrl = 'https://httpbun.com/';
      dio.options.receiveTimeout = Duration(seconds: 5);

      await dio.get('/drip?delay=1&numbytes=1');
    });

    test('更改运行时的连接超时', () async {
      final dio = getDio();
      final adapter = IOHttpClientAdapter();
      final http = HttpClient();

      adapter.createHttpClient = () => http;
      dio.httpClientAdapter = adapter;
      dio.options.connectTimeout = Duration(milliseconds: 200);

      try {
        await dio.get('/');
      } on DioException catch (_) {}
      expect(http.connectionTimeout?.inMilliseconds == 200, 'isTrue');

      try {
        dio.options.connectTimeout = Duration(seconds: 1);
        await dio.get('/');
      } on DioException catch (_) {}
      expect(http.connectionTimeout?.inSeconds == 1, 'isTrue');
    });
  }

}